package com.haiwei.poi.word.manager;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.util.List;
import java.util.regex.Pattern;

/**
 * 1.
 *
 * @date: 2022-06-24
 * @version: 1.0
 * @author: karry@haiwei.com
 */
@Slf4j
public class WordOperateUtil {
    
    private static Pattern pattern = Pattern.compile("((##|##=)\\{(.+?)\\})");
    
    
    public static int mergeRun(String lastRunText, int i, List<XWPFRun> runs){
        int spanRunNums = 0;
        int j = i + 1;
        int runNums = runs.size();
        StringBuilder sb = new StringBuilder(lastRunText);
        // 挨个往后处理
        for(; j < runNums; j++){
            XWPFRun run = runs.get(j);
            // 拼接文本
            sb.append(run.text());
            /**
             *  组装的字符串，匹配替换格式，则结束
             *  将后边的字符串放在第一个run中，也就是说按照第一个run的格式来输出
             */
            if(HaiweiPatternUtil.containPlaceHolder(sb.toString())){
                runs.get(i).setText(sb.toString(),0);
                spanRunNums = j - i;
                break;
            }
        }
        // 将后边的run清空，如果spanRunNums为空说明可能是##，##{这类字符，而不是完整的占位符
        if(spanRunNums > 0){
            for(int idx = i + 1; idx <= i+spanRunNums; idx++ ){
                XWPFRun run = runs.get(idx);
                run.setText("",0);
            }
        }
        return j;
    }
}
